const express = require('express');
const router =  express.Router();
const resumeMapper = require('../mapper/resumeMapper');
const conn = require('../utils/conn');
const jwt = require('../utils/jwt');

router.post('/v1/resume', (req, res) => {
  const validate = jwt.validate(req, res);
  if(validate < 1) {
    return;
  }

  const { id, fullName, gender, birthday, home, city, salary, tel, email, emergeName, emergeTel, educationHistory, workHistory, projectHistory, awardHistory, selfEvaluate } = req.body;
  if(validate != id) {
    return res.send({ code: 418, err: "I'm a teapot" });
  }
  
  const items = [ id, fullName, gender, birthday, home, city, salary, tel, email, emergeName, emergeTel, educationHistory, workHistory, projectHistory, awardHistory, selfEvaluate ];
  conn.query(resumeMapper.add, items, (err, data) => {
    if(err) {
      res.send({ code: 500, err });
    } if(data) {
      res.send({ code: 200, data });
    }
  });
});

router.put('/v1/resume', (req, res) => {
  const validate = jwt.validate(req, res);
  if(validate < 1) {
    return;
  }

  const { fullName, gender, birthday, home, city, salary, tel, email, emergeName, emergeTel, educationHistory, workHistory, projectHistory, awardHistory, selfEvaluate, id } = req.body;
  if(validate != id) {
    return res.send({ code: 418, err: "I'm a teapot" });
  }
  const items = [ fullName, gender, birthday, home, city, salary, tel, email, emergeName, emergeTel, educationHistory, workHistory, projectHistory, awardHistory, selfEvaluate, id ];
  conn.query(resumeMapper.update, items, (err, data) => {
    if(err) {
      res.send({ code: 500, err });
    } if(data) {
      res.send({ code: 200, data });
    }
  });
});

router.get('/v1/resume/:id', (req, res) => {
  const validate = jwt.validate(req, res);
  if(validate < 1) {
    return;
  }

  const id = req.params.id;
  conn.query(resumeMapper.select, [ id ], (err, data) => {
    if(err) {
      res.send({ code: 500, err });
    } if(data) {
      res.send({ code: 200, data: data.length ? data[0] : {} });
    }
  });
});

module.exports = router;